package mn.slide.labmed;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import mn.slide.labmed.database.ItemsStatics;

import android.app.Activity;
import android.content.Intent;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;

public class LabMed extends Activity
{
	public static String	PATH			= "/data/data/mn.slide.labmed/databases/";
	public static String	DATABASE_PATH	= PATH + "Labmed.sqlite";
	protected int			_splashTime		= 800;
	private Thread			splashTread;

	@Override
	public void onCreate( Bundle savedInstanceState )
	{
		super.onCreate(savedInstanceState);

		setContentView(R.layout.splash);
		createDatabase();
		ItemsStatics itemsStatics = new ItemsStatics();
		itemsStatics.initDb(this);
		final LabMed sPlashScreen = this;
		splashTread = new Thread()
		{
			@Override
			public void run()
			{
				try
				{
					synchronized (this)
					{

						wait(_splashTime);
					}

				}
				catch (InterruptedException e)
				{
					e.printStackTrace();
				}
				finally
				{
					finish();
					Intent i = new Intent();
					i.setClass(sPlashScreen, RootViewActivity.class);
					startActivity(i);

				}
			}
		};

		splashTread.start();
	}

	@Override
	public boolean onTouchEvent( MotionEvent event )
	{
		if (event.getAction() == MotionEvent.ACTION_DOWN)
		{
			synchronized (splashTread)
			{
				splashTread.notifyAll();
			}
		}
		return true;
	}

	public void createDatabase()
	{
		Log.d("createDatabase", "createDatabase");
		File path = new File(PATH);
		if (!path.exists())
			path.mkdirs();
		File file = new File(DATABASE_PATH);
		;
		if (!file.exists())
		{
			AssetManager assetManager = getAssets();
			try
			{
				byte buf[] = new byte[1024 * 1024];
				OutputStream outputStream = new FileOutputStream(DATABASE_PATH);
				for (int i = 0; i < 2; i++)
				{
					InputStream inputStream = assetManager.open("Labmed.sqlite" + i);
					inputStream.read(buf);
					outputStream.write(buf);
					inputStream.close();
				}
				outputStream.flush();
				outputStream.close();
				Log.d("YES", "YES");
			}
			catch (IOException e)
			{
				Log.d("tag", e.getMessage());
			}
		}
	}

}